package cn.com.woxitech.dev.controller.api;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;

import cn.com.woxitech.dev.common.APIResult;
import cn.com.woxitech.dev.common.APIResultFactory;
import cn.com.woxitech.dev.common.CodeUtils;
import cn.com.woxitech.dev.common.Const;
import cn.com.woxitech.dev.common.EncryptionUtils;
import cn.com.woxitech.dev.common.HttpClientUtils;
import cn.com.woxitech.dev.common.JSONUtils;
import cn.com.woxitech.dev.common.QiniuPhotoUploadUtils;
import cn.com.woxitech.dev.common.StrUtils;
import cn.com.woxitech.dev.model.Lecture;
import cn.com.woxitech.dev.model.QiniuUploadResult;
import cn.com.woxitech.dev.model.RoomManager;
import cn.com.woxitech.dev.model.WmChathistoryFetch;
import cn.com.woxitech.dev.model.gen.WeixinApiAccessToken;
import cn.com.woxitech.dev.model.gen.WmApp;
import cn.com.woxitech.dev.model.gen.WmCatalog;
import cn.com.woxitech.dev.model.gen.WmLecture;
import cn.com.woxitech.dev.model.gen.WmLecturePage;
import cn.com.woxitech.dev.model.gen.WmRoom;
import cn.com.woxitech.dev.model.gen.WmUser;
import cn.com.woxitech.dev.service.AppService;
import cn.com.woxitech.dev.service.CatalogService;
import cn.com.woxitech.dev.service.LecturePageService;
import cn.com.woxitech.dev.service.LectureService;
import cn.com.woxitech.dev.service.OrganizationService;
import cn.com.woxitech.dev.service.PrivilegeService;
import cn.com.woxitech.dev.service.QiniuService;
import cn.com.woxitech.dev.service.RoomService;
import cn.com.woxitech.dev.service.SMSCodeService;
import cn.com.woxitech.dev.service.SettingService;
import cn.com.woxitech.dev.service.UserService;
import cn.com.woxitech.dev.service.WeixinService;

@RestController
@RequestMapping("/basic")
public class UploadLUYANController {
	@Autowired
	WeixinService weixinService;
	@Autowired
	SettingService settingService;
	@Autowired
	PrivilegeService privilegeService;
	@Autowired
	QiniuService qiniuService;
	@Autowired
	RoomService roomService;
	@Autowired
	LectureService lectureService;
	@Autowired
	LecturePageService lecturePageService;
	@Autowired
	UserService userService;
	@Autowired
	SMSCodeService smsCodeService;
	@Autowired
	OrganizationService organizationService;
	@Autowired
	CatalogService catalogService;
	@Autowired
	AppService appService;

	@RequestMapping(value = "/native/upload_ppt/folder/{folder}", method = RequestMethod.POST)
	public Object native_upload_ppt(@RequestParam("file") MultipartFile file, @PathVariable String folder) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			String _folder = "ppt";
			if (folder != null && !folder.equals("")) {
				_folder = folder;
			}

			String filebase = StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.ATTACHMENT_PATH))
					+ "/" + _folder + "/";
			// filebase = filebase.replaceAll("\\", "\\\\");
			byte[] bytes = file.getBytes();
			String key = UUID.randomUUID().toString();
			String filename = filebase + key + ".ppt";

			File f_path = new File(filebase);
			if (!f_path.exists()) {
				f_path.mkdirs();
			}
			File f_key = new File(f_path, key);
			if (!f_key.exists()) {
				f_key.createNewFile();
			}

			FileOutputStream fos = new FileOutputStream(f_key);

			fos.write(bytes);

			fos.flush();
			fos.close();

			String relative_path = "/attachment/" + _folder + "/" + key;

			mp.put("key", key);
			mp.put("path", relative_path);

			return APIResultFactory.created(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail("");
		}
	}
	

	@RequestMapping(value = "/native/upload_img/folder/{folder}", method = RequestMethod.POST)
	public Object native_upload_img(@RequestParam("file") MultipartFile file, @PathVariable String folder) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			String _folder = "default";
			if (folder != null && !folder.equals("")) {
				_folder = folder;
			}

			String filebase = StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.ATTACHMENT_PATH))
					+ "/" + _folder + "/";
			// filebase = filebase.replaceAll("\\", "\\\\");
			byte[] bytes = file.getBytes();
			String key = UUID.randomUUID().toString();
			String filename = filebase + key;

			File f_path = new File(filebase);
			if (!f_path.exists()) {
				f_path.mkdirs();
			}
			File f_key = new File(f_path, key);
			if (!f_key.exists()) {
				f_key.createNewFile();
			}

			FileOutputStream fos = new FileOutputStream(f_key);

			fos.write(bytes);

			fos.flush();
			fos.close();

			String relative_path = "/attachment/" + _folder + "/" + key;

			mp.put("key", key);
			mp.put("path", relative_path);

			return APIResultFactory.created(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail("");
		}
	}

	@RequestMapping(value = "/qiniu/upload_img/folder/{folder}", method = RequestMethod.POST)
	public Object qiniu_upload_img(@RequestParam("file") MultipartFile file, @PathVariable String folder) {

		
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			byte[] bytes = file.getBytes();
			String filename = "nttcimg_" + UUID.randomUUID().toString()+".jpg";
			// 密钥配置
			Auth auth = Auth.create(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY);
			String bucket = Const.Bucket_HAOJSQINIU;
			// 创建上传对象
			UploadManager uploadManager = new UploadManager();
			
			String uploadToken = auth.uploadToken(bucket);
			
			uploadManager.put(bytes, filename, uploadToken);
			

			mp.put("key", filename);
			mp.put("path",  Const.QINIU_BASE_URL + "/" + filename);

			return APIResultFactory.created(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
    
	//供合并字节用
	public byte[] TotalBytes=new byte[0];
	//上传七牛
	@RequestMapping(value = "/qiniu/upload_vid/folder/{roomuuid}", method = RequestMethod.POST)
	public Object qiniu_upload_vid(@RequestParam("file") MultipartFile file, @PathVariable String roomuuid) {

		
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			byte[] bytes = file.getBytes();
			String filename = "localvid_" + UUID.randomUUID().toString()+".mp4";
			Auth auth = Auth.create(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY);
			String bucket = Const.Bucket_HAOJSQINIU;
			UploadManager uploadManager = new UploadManager();
			String uploadToken = auth.uploadToken(bucket);
			
			//前端传来碎片在这里合并字节
			//判断如果是完整的5M字节则合并，小于5M则为最后一片
			if(bytes.length==5242880){
				byte[] byte_3=new byte[TotalBytes.length+bytes.length];
				System.arraycopy(TotalBytes, 0, byte_3, 0, TotalBytes.length);
				System.arraycopy(bytes, 0, byte_3, TotalBytes.length, bytes.length);
				TotalBytes=byte_3;
			}
			else{
				byte[] byte_3=new byte[TotalBytes.length+bytes.length];
				System.arraycopy(TotalBytes, 0, byte_3, 0, TotalBytes.length);
				System.arraycopy(bytes, 0, byte_3, TotalBytes.length, bytes.length);
				TotalBytes=byte_3;
				uploadManager.put(TotalBytes, filename, uploadToken);
				TotalBytes=new byte[0];
				String vid_url=Const.QINIU_BASE_URL+'/'+filename;
				System.out.println("视频链接："+vid_url);
				String mybody="{\"id\":\"\",\"pageurl\":\""+vid_url+"\",\"roomuuid\":\""+roomuuid+"\"}";
				//链接传递到阿里云服务器并在页面反馈
				AliDB(mybody);
			}

			mp.put("key", filename);
			mp.put("path",  Const.QINIU_BASE_URL + "/" + filename);

			return APIResultFactory.created(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	//上传阿里云并在前端显示
	private void AliDB( String body) {
		JsonNode jsonNode;
		
		try {
			jsonNode = JSONUtils.toJson(body);
			int id = jsonNode.get("id").asInt();
			String pageurl = jsonNode.get("pageurl").asText();
			String roomuuid = jsonNode.get("roomuuid").asText();
			if(id != 0){
				WmLecturePage lp = this.lecturePageService.selectByPrimaryKey(id);
				lp.setPageurl(pageurl);
				this.lecturePageService.updateByPrimaryKey(lp);
			}else{
				String lectureid = this.lectureService.getLectureByRoomUuid(roomuuid).getUuid();
				WmLecturePage lp = new WmLecturePage();
				lp.setLectureid(lectureid);
				lp.setNum(12);
				lp.setType("video");
				lp.setPageurl(pageurl);
				lp.setTime(new Date(System.currentTimeMillis()));
				this.lecturePageService.insertLecturePage(lp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	@RequestMapping(value = "/qiniu/upload_audio/folder/{folder}", method = RequestMethod.POST)
	public Object qiniu_upload_audio(@RequestParam("file") MultipartFile file, @PathVariable String folder) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			byte[] bytes = file.getBytes();
			String filename = "app" + UUID.randomUUID().toString();
			// 密钥配置
			Auth auth = Auth.create(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY);
			String bucket = Const.Bucket_WMHISTORY;
			// 创建上传对象
			UploadManager uploadManager = new UploadManager();
			// 设置转码操作参数
			String fops = "avthumb/mp3/acodec/libmp3lame";
			// 设置转码的队列
			String pipeline = Const.PIPELINE_NAME;
			String urlbase64 = UrlSafeBase64.encodeToString(bucket + ":" + filename + ".mp3");
			String pfops = fops + "|saveas/" + urlbase64;
			// 简单上传，使用默认策略，只需要设置上传的空间名就可以了
			String token = getUpToken(auth, bucket, pfops, pipeline);
			// String token = auth.uploadToken(HJSConstants.Bucket_WMHISTORY);
			// 调用put方法上传
			Response res = uploadManager.put(bytes, filename + ".amr", token);

			// Response res = uploadManager.put(FilePath, null, token);
			// 打印返回的信息

			mp.put("key", filename+".mp3");
			mp.put("path", Const.QINIU_CHAT_BASE_URL + "/" + filename+".mp3");
			return APIResultFactory.success(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail();
		}
	}

	public static String getUpToken(Auth auth, String bucketname, String pfops, String pipeline) {
		return auth.uploadToken(bucketname, null, 3600,
				new StringMap().putNotEmpty("persistentOps", pfops).putNotEmpty("persistentPipeline", pipeline), true);
	}

	@RequestMapping(value = "/native/upload_audio/folder/{folder}", method = RequestMethod.POST)
	public Object native_upload_audio(@RequestParam("file") MultipartFile file, @PathVariable String folder) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			String _folder = "default";
			if (folder != null && !folder.equals("")) {
				_folder = folder;
			}

			String filebase = StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.ATTACHMENT_PATH))
					+ "/" + _folder + "/";
			// filebase = filebase.replaceAll("\\", "\\\\");
			byte[] bytes = file.getBytes();
			String key = UUID.randomUUID().toString();
			String filename = filebase + key;

			File f_path = new File(filebase);
			if (!f_path.exists()) {
				f_path.mkdirs();
			}
			File f_key = new File(f_path, key);
			if (!f_key.exists()) {
				f_key.createNewFile();
			}

			FileOutputStream fos = new FileOutputStream(f_key);

			fos.write(bytes);

			fos.flush();
			fos.close();

			String relative_path = "/attachment/" + _folder + "/" + key;

			mp.put("key", key);
			mp.put("path", relative_path);

			return APIResultFactory.created(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail("");
		}
	}
}
